package com.security.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.jsonfilter.SerializeField;
import com.example.utils.PinyinUtils;
import com.security.IsAdmin;
import com.security.domain.*;
import com.security.domain.vo.UserRoleVo;
import com.security.domain.vo.UserVo;
import com.security.service.SysMenuService;
import com.security.service.SysRoleService;
import com.security.service.SysUserRoleService;
import com.security.service.SysUserService;

import com.security.util.ResultUtil;
import com.security.util.SecurityUtil;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 15:28
 * @since JDK 1.8
 */
@RestController
@Validated
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 管理端信息
     * @Author Sans
     * @CreateTime 2019/10/2 14:22
     * @Return Map<String,Object> 返回数据MAP
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public Map<String,Object> userLogin(){
        Map<String,Object> result = new HashMap<>();
        SelfUserEntity userDetails = SecurityUtil.getUserInfo();
        result.put("title","管理端信息");
        result.put("data",userDetails);
        return ResultUtil.resultSuccess(result);
    }

    /**
     * 拥有ADMIN或者USER角色可以访问
     * @Author Sans
     * @CreateTime 2019/10/2 14:22
     * @Return Map<String,Object> 返回数据MAP
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Map<String,Object> list(){
        Map<String,Object> result = new HashMap<>();
        List<SysUserEntity> sysUserEntityList = sysUserService.list();
        result.put("title","拥有用户或者管理员角色都可以查看");
        result.put("data",sysUserEntityList);
        return ResultUtil.resultSuccess(result);
    }

    /**
     * 拥有ADMIN和USER角色可以访问
     * @Author Sans
     * @CreateTime 2019/10/2 14:22
     * @Return Map<String,Object> 返回数据MAP
     */
    @PreAuthorize("hasRole('ADMIN') and hasRole('USER')")
    @RequestMapping(value = "/menuList",method = RequestMethod.GET)
    public Map<String,Object> menuList(){
        Map<String,Object> result = new HashMap<>();
        List<SysMenuEntity> sysMenuEntityList = sysMenuService.list();
        result.put("title","拥有用户和管理员角色都可以查看");
        result.put("data",sysMenuEntityList);
        return ResultUtil.resultSuccess(result);
    }


    /**
     * 拥有sys:user:info权限可以访问
     * hasPermission 第一个参数是请求路径 第二个参数是权限表达式
     * @Author Sans
     * @CreateTime 2019/10/2 14:22
     * @Return Map<String,Object> 返回数据MAP
     */
    @PreAuthorize("hasPermission('/admin/userList','sys:user:info')")
    @RequestMapping(value = "/userList",method = RequestMethod.GET)
    public Map<String,Object> userList(){
        Map<String,Object> result = new HashMap<>();
        List<SysUserEntity> sysUserEntityList = sysUserService.list();
        result.put("title","拥有sys:user:info权限都可以查看");
        result.put("data",sysUserEntityList);
        return ResultUtil.resultSuccess(result);
    }

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    /**
     * 拥有ADMIN角色和sys:role:info权限可以访问
     * @Author Sans
     * @CreateTime 2019/10/2 14:22
     * @Return Map<String,Object> 返回数据MAP
     */
    @PreAuthorize("hasRole('ADMIN') and hasPermission('/admin/adminRoleList','sys:role:info')")
    @RequestMapping(value = "/adminRoleList",method = RequestMethod.GET)
    public Map<String,Object> adminRoleList(){
        Map<String,Object> result = new HashMap<>();
        List<SysRoleEntity> sysRoleEntityList = sysRoleService.list();
        result.put("title","拥有ADMIN角色和sys:role:info权限可以访问");
        result.put("data",sysRoleEntityList);
        return ResultUtil.resultSuccess(result);
    }

    @ApiModelProperty("角色列表")
    @GetMapping("rolelist")
    @IsAdmin
    public JSONObject userRoleListController(){
        List<SysRoleEntity> sysRoleEntities=sysRoleService.list();
        return ResultUtil.resultObjectJSON(0,"success",sysRoleEntities);
    }


    @ApiModelProperty("角色赋予")
    @IsAdmin
    @PostMapping("adduserrole")
    public JSONObject addUserRoleController(@RequestBody UserRoleVo userRoleVo){
        String[] rids=userRoleVo.getRid();
        List<SysUserRoleEntity> sysUserRoleEntityList=sysUserRoleService.selectUserRoleRoleEntity(userRoleVo.getUid(),userRoleVo.getRid());
        List<SysUserRoleEntity> sysUserRoleEntityList1=new ArrayList<>();
        if(sysUserRoleEntityList==null){
            sysUserRoleEntityList=new ArrayList<>();
        }
        List<Long> ridList=sysUserRoleEntityList.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
        for (int i = 0; i < rids.length ; i++) {
            if(ridList.contains(Long.valueOf(rids[i]))){
                continue;
            }
            SysUserRoleEntity sysUserRoleEntity=new SysUserRoleEntity();
            sysUserRoleEntity.setUserId(Long.valueOf(userRoleVo.getUid()));
            sysUserRoleEntity.setRoleId(Long.valueOf(rids[i]));
            sysUserRoleEntityList1.add(sysUserRoleEntity);
        }
        if(sysUserRoleEntityList1.size()>0){
            sysUserRoleService.saveBatch(sysUserRoleEntityList1);
        }
        return ResultUtil.resultCodeJSON(200,"添加成功");
    }



    @ApiModelProperty("角色添加")
    @IsAdmin
    @PostMapping("addrole")
    public JSONObject addRoleController(@RequestParam("roleName")String roleName){
        roleName= PinyinUtils.toPinYinFirstUpper(roleName,"");
        SysRoleEntity sysRoleEntity=sysRoleService.getSysRoleEntityByUserName(roleName);
        if(sysRoleEntity!=null){
            return ResultUtil.resultCodeJSON(1,"角色已经存在");
        }
        SysRoleEntity sysRoleEntity1=new SysRoleEntity();
        sysRoleEntity1.setRoleName(roleName);
        sysRoleService.save(sysRoleEntity1);
        return ResultUtil.resultCodeJSON(200,"添加成功");
    }


    @ApiModelProperty("用户列表")
    @IsAdmin
    @GetMapping("userlist")
    @SerializeField(clazz = SysUserEntity.class, includes = {"id", "username","realname","phone","address","createTime"})
    public JSONObject userListPageController(@Min (1)@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                             @Max (100)@RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                             @RequestParam(value = "keyword",required = false)String keyword){
        SelfUserEntity userEntity=SecurityUtil.getUserInfo();
        System.out.println(userEntity);
        LambdaQueryWrapper<SysUserEntity> sysUserEntityLambdaQueryWrapper=new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(keyword)){
            sysUserEntityLambdaQueryWrapper.like(SysUserEntity::getUsername,keyword);
            sysUserEntityLambdaQueryWrapper.or().eq(SysUserEntity::getRealname,keyword);
            sysUserEntityLambdaQueryWrapper.or().like(SysUserEntity::getAddress,keyword);
            sysUserEntityLambdaQueryWrapper.or().like(SysUserEntity::getPhone,keyword);
        }
        IPage<SysUserEntity> sysUserEntityIPage=sysUserService.page(new Page(pageNum,pageSize),sysUserEntityLambdaQueryWrapper);
        return ResultUtil.resultObjectJSON(200,"success",sysUserEntityIPage);
    }

    @ApiModelProperty("用户新增")
    @IsAdmin
    @PostMapping("adduser")
    public JSONObject addUserController(@RequestBody UserVo userVo){
        SysUserEntity sysUserEntity=sysUserService.selectUserByName(userVo.getUsername());
        if(sysUserEntity!=null){
            return ResultUtil.resultCodeJSON(1,"账号已经存在");
        }
        if(!userVo.getAgainpassword().equals(userVo.getPassword())){
            return ResultUtil.resultCodeJSON(1,"两次密码不一致");
        }
        SysUserEntity userEntity=new SysUserEntity();

        BeanUtils.copyProperties(userVo,userEntity);
        userEntity.setPassword(bCryptPasswordEncoder.encode(userEntity.getPassword()));
        sysUserService.save(userEntity);
        return ResultUtil.resultCodeJSON(0,"添加成功");
    }






}
